<template>
  <div class="login_container">
    <div class="login_box">
      <div class="avatar_box">
        <img
          src="@/assets/logo.png"
          alt=""
        />
      </div>
      <el-form
        ref="loginform"
        :model="loginform"
        label-width="0px"
        class="login_form"
        :rules="rules"
      >
        <el-form-item prop="username">
          <el-input
            @keyup.enter.native="login"
            prefix-icon="el-icon-user-solid"
            v-model="loginform.username"
          ></el-input>
        </el-form-item>
        <el-form-item prop="pass">
          <el-input
            @keyup.enter.native="login"
            type="password"
            prefix-icon="el-icon-trophy"
            v-model="loginform.password"
          ></el-input>
        </el-form-item>
        <el-form-item class="btn">
          <el-button
            type="primary"
            @click="login"
          >登录</el-button>
          <el-button
            type="info"
            @click="clear"
          >清空</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
export default {
  methods: {
    clear () {
      this.$refs.loginform.resetFields()
      this.loginform.username = ''
      this.loginform.password = ''
    },
    login () {
      this.$refs.loginform.validate(async (valid) => {
        if (!valid) return
        const { data: res } = await this.$http.post('login', this.loginform)
        if (res.meta.status !== 200) {
          return this.$message.error('登录失败！')
        }
        this.$message.success('登录成功！')
        window.sessionStorage.setItem('token',res.data.token)
        this.$router.push('/home')
      })
    },
  },
  data () {
    return {
      loginform: {
        username: "",
        password: "",
      },
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
      },
    };
  },
};
</script>

<style lang="less" scoped>
.login_container {
  background-color: #2b5b6b;
  height: 100%;
}
.login_box {
  width: 450px;
  height: 300px;
  background-color: #fff;
  position: absolute;
  left: 50%;
  top: 50%;
  border-radius: 3px;
  transform: translate(-50%, -50%);
  .avatar_box {
    width: 130px;
    height: 130px;
    border-radius: 50%;
    padding: 10px;
    box-shadow: 0 0 10px #ddd;
    position: absolute;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: #fff;
    img {
      width: 100%;
      height: 100%;
      border-radius: 50%;
      background-color: #eee;
    }
  }
  .login_form {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 0 20px;
    box-sizing: border-box;
    .btn {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
